package com.sjgtw.cloud.system.controller;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.sjgtw.cloud.common.core.constant.Constants;
import com.sjgtw.cloud.common.core.constant.UserConstants;
import com.sjgtw.cloud.common.core.utils.SecurityUtils;
import com.sjgtw.cloud.common.core.utils.StringUtils;
import com.sjgtw.cloud.common.core.web.controller.BaseController;
import com.sjgtw.cloud.common.core.web.domain.AjaxResult;
import com.sjgtw.cloud.common.log.annotation.Log;
import com.sjgtw.cloud.common.log.enums.BusinessType;
import com.sjgtw.cloud.common.security.annotation.PreAuthorize;
import com.sjgtw.cloud.system.domain.SysMenu;
import com.sjgtw.cloud.system.service.ISysMenuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;

/**
 * <p>Title: 菜单信息管理</p>
 * <p>Description: </p>
 * @author Admin
 * @date 2020-7-4
 */
@Api(value = "菜单信息管理",tags = {"菜单信息管理接口"}) 
@RestController
@RequestMapping("/menu")
public class SysMenuController extends BaseController
{
    @Autowired
    private ISysMenuService menuService;

    /**
     * <p>Title: 获取菜单列表--不分页</p>
     * <p>Description: </p>
     * @param menu
     * @return
     */
    @ApiOperation("获取菜单列表--不分页")
    @PreAuthorize(hasPermi = "system:menu:list")
    @GetMapping("/list")
    public AjaxResult list(SysMenu menu)
    {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuList(menu, userId);
        return AjaxResult.success(menus);
    }

    /**
     * <p>Title: 根据菜单ID获取菜单信息</p>
     * <p>Description: </p>
     * @param menuId
     * @return
     */
    @ApiOperation("根据菜单ID获取菜单信息")
	@ApiImplicitParam(name = "menuId", value = "菜单ID", required = true, dataType = "Long", paramType = "path")
    @PreAuthorize(hasPermi = "system:menu:query")
    @GetMapping(value = "/{menuId}")
    public AjaxResult getInfo(@PathVariable Long menuId)
    {
        return AjaxResult.success(menuService.selectMenuById(menuId));
    }

    /**
     * <p>Title: 菜单下拉树</p>
     * <p>Description: 前端所需要的菜单下拉树</p>
     * @param menu
     * @return
     */
    @ApiOperation("菜单下拉树")
    @GetMapping("/treeselect")
    public AjaxResult treeselect(SysMenu menu)
    {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuList(menu, userId);
        return AjaxResult.success(menuService.buildMenuTreeSelect(menus));
    }

    /**
     * <p>Title: 角色对应的菜单列表树</p>
     * <p>Description: 角色对应的菜单列表树</p>
     * @param roleId
     * @return
     */
    @ApiOperation("角色对应的菜单列表树")
    @ApiImplicitParam(name = "roleId", value = "角色ID", required = true, dataType = "Long", paramType = "path")
    @GetMapping(value = "/roleMenuTreeselect/{roleId}")
    public AjaxResult roleMenuTreeselect(@PathVariable("roleId") Long roleId)
    {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuList(userId);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("checkedKeys", menuService.selectMenuListByRoleId(roleId));
        ajax.put("menus", menuService.buildMenuTreeSelect(menus));
        return ajax;
    }

    /**
     * <p>Title: 新增菜单</p>
     * <p>Description: </p>
     * @param menu
     * @return
     */
    @ApiOperation("新增菜单")
    @PreAuthorize(hasPermi = "system:menu:add")
    @Log(title = "菜单管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysMenu menu)
    {
        if (UserConstants.NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu)))
        {
            return AjaxResult.error("新增菜单'" + menu.getMenuName() + "'失败，菜单名称已存在！");
        }
        else if (UserConstants.YES_FRAME.equals(menu.getIsFrame())
                && !StringUtils.startsWithAny(menu.getPath(), Constants.HTTP, Constants.HTTPS))
        {
            return AjaxResult.error("新增菜单'" + menu.getMenuName() + "'失败，请求地址头必须是http(s)开头！");
        }
        menu.setCreateBy(SecurityUtils.getUsername());
        return toAjax(menuService.insertMenu(menu));
    }

    /**
     * <p>Title: 修改菜单</p>
     * <p>Description: </p>
     * @param menu
     * @return
     */
    @ApiOperation("修改菜单")
    @PreAuthorize(hasPermi = "system:menu:edit")
    @Log(title = "菜单管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysMenu menu)
    {
        if (UserConstants.NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu)))
        {
            return AjaxResult.error("修改菜单'" + menu.getMenuName() + "'失败，菜单名称已存在！");
        }
        else if (UserConstants.YES_FRAME.equals(menu.getIsFrame())
                && !StringUtils.startsWithAny(menu.getPath(), Constants.HTTP, Constants.HTTPS))
        {
            return AjaxResult.error("修改菜单'" + menu.getMenuName() + "'失败，请求地址头必须是http(s)开头！");
        }
        else if (menu.getMenuId().equals(menu.getParentId()))
        {
            return AjaxResult.error("修改菜单'" + menu.getMenuName() + "'失败，父级部门不能选自己！");
        }
        menu.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(menuService.updateMenu(menu));
    }

    /**
     * <p>Title: 删除菜单</p>
     * <p>Description: </p>
     * @param menuId
     * @return
     */
    @ApiOperation("删除菜单")
    @ApiImplicitParam(name = "menuId", value = "菜单ID", required = true, dataType = "Long", paramType = "path")
    @PreAuthorize(hasPermi = "system:menu:remove")
    @Log(title = "菜单管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{menuId}")
    public AjaxResult remove(@PathVariable("menuId") Long menuId)
    {
        if (menuService.hasChildByMenuId(menuId))
        {
            return AjaxResult.error("删除失败，该菜单下还有子菜单！");
        }
        if (menuService.checkMenuExistRole(menuId))
        {
            return AjaxResult.error("删除失败，该菜单使用中！");
        }
        return toAjax(menuService.deleteMenuById(menuId));
    }

    /**
     * <p>Title: 获取路由信息</p>
     * <p>Description: </p>
     * @param menuId
     * @return
     */
    @ApiOperation("获取路由信息")
    @GetMapping("/getRouters")
    public AjaxResult getRouters()
    {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }
}